package gossip.v2.message;

import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import gossip.v2.util.SerializationUtils;
import gossip.v2.cluster.GossipNode;
import lombok.Getter;

import java.util.Collections;
import java.util.Map;

@Getter
@ProtobufClass
public class SyncMessage extends GossipMessage {
    private Map<String, Long> versions;
    private Map<String, byte[]> stateValues;
    private boolean fullSync;

    public SyncMessage() {
        type = Type.SYNC;
    }

    public SyncMessage(GossipNode sender, Map<String, Long> versions,
                       Map<String, byte[]> stateValues, boolean fullSync) {
        this();
        setSender(sender);
        this.versions = versions;
        this.stateValues = stateValues;
        this.fullSync = fullSync;
    }

    private void setSender(GossipNode sender) {
        this.sender = sender;
        this.senderId = sender != null ? sender.getNodeId() : null;
    }

    public Map<String, Long> getVersions() {
        return versions != null ? Collections.unmodifiableMap(versions) : Collections.emptyMap();
    }

    public Map<String, byte[]> getStateValues() {
        return stateValues != null ? Collections.unmodifiableMap(stateValues) : Collections.emptyMap();
    }

    public <T> T getValueAs(String key, Class<T> clazz) {
        byte[] bytes = stateValues != null ? stateValues.get(key) : null;
        return bytes != null ? SerializationUtils.deserialize(bytes, clazz) : null;
    }

    public byte[] getValueBytes(String key) {
        return stateValues != null ? stateValues.get(key) : null;
    }

}
